package XmlNetty;

import java.util.HashMap;
import java.util.Map;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;


public class byteToXmlServerHandle extends SimpleChannelHandler {
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub	
		Channel newChannel = e.getChannel();
		System.out.println("new connection "+newChannel.getRemoteAddress().toString());
		byteToXmlServer.channelMap.put(newChannel.getRemoteAddress().toString(), newChannel);
		newChannel.write(new XmlPackge("connectioned", new byte[0]));	
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		// TODO Auto-generated method stub
		XmlPackge xmlpackge = (XmlPackge)e.getMessage();
		String filename = xmlpackge.getJdxh();		
		byte[] bfile = XmlUtil.readXml(xmlpackge.getJdxh());
		System.out.println(xmlpackge.getJdxh());
		e.getChannel().write(new XmlPackge(filename, bfile));	
	}

	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		Channel closedChannel = e.getChannel();
		closedChannel.close();
		System.out.println("connection closed"+closedChannel.getRemoteAddress().toString());
		byteToXmlServer.channelMap.remove(closedChannel.getRemoteAddress().toString());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		e.getCause().printStackTrace();
		Channel exceptionChannel = e.getChannel();
		exceptionChannel.close();
		byteToXmlServer.channelMap.remove(exceptionChannel.getRemoteAddress().toString());
	}
}
